#!/usr/bin/env python
import os.path
import sys
import re

import unittest
import coverage

def discover_tests (test_source, include_package=None):
    testfiles = []
    for root, _, files in os.walk(test_source):
        if include_package and include_package not in root:
            continue
        
        for file_name in files:
            if file_name.endswith('tests.py'):
                module = os.path.join(root, file_name)
                module = module.replace(test_source, "")
                module = module.replace(os.sep, '.')
                module = module[1:-3]
                print "\tImporting test module '%s'" % module
                __import__(module)
                testfiles.append(module)
    return testfiles

def run_tests (test_source, include_package=None):
    print "Discovering tests"
    test_modules = discover_tests(test_source, include_package)
    tests = unittest.defaultTestLoader.loadTestsFromNames(test_modules)
    print "Running tests"
    result = unittest.TextTestRunner(stream=sys.stdout).run(tests)
    return len(result.failures) + len(result.errors)

if __name__ == '__main__':
    sys.path.append(os.path.join("src", "main", "python"))
    sys.path.append(os.path.join("src", "unittest", "python"))

    print "=" * 60
    print "RUNNING TESTS"
    print "=" * 60
    coverage.erase()
    coverage.start()
    result = run_tests(os.path.join("src", "unittest", "python"))
    coverage.stop()
    coverage.analysis(sys.modules["rpmconfigmaker.tokenreplacer"])
    
    print "=" * 60
    print "COVERAGE"
    print "=" * 60
    coverage.report([sys.modules["rpmconfigmaker.tokenreplacer"]])
    
    sys.exit(result)
    